package strategys;

import config.ConfigReader;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FileLogStrategy implements LogStrategy {
    private String filePath;
    private SimpleDateFormat dateFormat;

    public FileLogStrategy() {
        ConfigReader configReader = ConfigReader.getInstance();
        this.filePath = configReader.getFileLogPath();
        this.dateFormat = new SimpleDateFormat(configReader.getLogFormat());
    }

    @Override
    public void log(String level, String message, StackTraceElement[] stackTraceElements) {
        String timestamp = dateFormat.format(new Date());
        File file = new File(filePath);

        // 如果文件不存在，则创建文件
        if (!file.exists()) {
            try {
                file.getParentFile().mkdirs(); // 创建父目录
                file.createNewFile(); // 创建文件
            } catch (IOException e) {
                e.printStackTrace();
                return; // 如果创建文件失败，则不继续写入
            }
        }

        // 获取调用栈信息
        StackTraceElement caller = stackTraceElements[2];
        String className = caller.getClassName();
        String methodName = caller.getMethodName();
        int lineNumber = caller.getLineNumber();

        try (FileWriter writer = new FileWriter(filePath, true)) {
            writer.write("[" + timestamp + "] [" + level + "] [" + className + "." + methodName + ":" + lineNumber + "] " + message + "\n");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
